<template>
  <view class="sign-up-page">
    <view
      class="custom flex_center"
      :style="{ 'padding-top': vuex_phoneInfo.statusBarHeight + 'px' }"
    >
      <image class="btn-back" src="/static/common/image/btn_back.png" mode="widthFix" @click="goBack"></image>
      <image class="logo" src="https://cdc-file.risechina.com/img/2021/11/1635906037589.png" mode="widthFix"></image>
    </view>
    <view
      v-if="step !==2"
      class="banner" 
      :style="{ 'padding-top': vuex_phoneInfo.statusBarHeight + 43 + 'px' }"
    >
      <image class="img" src="https://cdc-file.risechina.com/img/2021/11/1635839717046.png" mode="widthFix"></image>
    </view>
    <view class="title" v-if="step !==2">
      <image class="title-img" src="/static/common/image/title.png" mode="widthFix"></image>
      <sign-up-progress
        :step="step"
      ></sign-up-progress>
    </view>
    <view class="form">
      <user-info-form
        v-if="step === 0"
        ref="userInfoForm"
      ></user-info-form>
      <sessiom-form
        v-if="step === 1"
        ref="sessiomForm"
      ></sessiom-form>
      <book-result
        v-if="step === 2"
      ></book-result>
    </view>
    <view class="btns-fix-bottom">
      <view v-if="step === 2" class="btns-box">
        <view class="btn" @click="userHandler(1)">活动详情</view>
        <view class="btn" @click="userHandler(2)">修改时间</view>
        <view class="btn" @click="userHandler(3)">取消预约</view>
      </view>
      <view v-if="step === 2" class="btn-sign-up" @click="goSaveImg">
        保存预约信息
      </view>  
      <view v-else class="btn-sign-up" @click="goNext">
        {{ step === 1 ? '确认预约' : '下一步' }}
      </view>  
    </view>
    <wxml-to-canvas width="400" height="700" id="widget" style="position: absolute;left: 0;top: 0; z-index: -1;opacity: 0"></wxml-to-canvas>
  </view>
</template>

<script>
import signUpProgress from './components/progress.vue'
import userInfoForm from './components/userInfoForm.vue'
import sessiomForm from './components/sessiomForm.vue'
import bookResult from './components/bookResult.vue'
import { wxml, style } from './wxmlToCanvas.js'
export default {
  components: {
    signUpProgress,
    userInfoForm,
    sessiomForm,
    bookResult
  },
  data() {
    return {
      step: 0
    }
  },
  onLoad() {
    this.widget = this.selectComponent('#widget')
    if ( this.vuex_userInfo.session_id ) {
      this.step = 2;
    }
  },
  methods: {
    goBack() {
      wx.navigateBack({
        delta: 1
      })
    },
    goNext() {
      // 第一步
      if (this.step === 0) {
        this.formDataUserInfo = this.$refs.userInfoForm.formDataUserInfo;
        const reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        let errorMsg = ''
        if (!this.formDataUserInfo.name) {
          errorMsg = '请填写姓名'
        } else if (!this.formDataUserInfo.mobile) {
          errorMsg = '请填写手机号'
        } else if (!reg_tel.test(this.formDataUserInfo.mobile)) {
          errorMsg = '请输入正确的手机号'
        } else if(!this.formDataUserInfo.checked) {
          errorMsg = '请阅读并勾选协议'
        }
        if (errorMsg) {
          uni.showToast({
            title: errorMsg,
            duration: 3000,
            icon: 'none'
          });
        } else {
          this.step ++;
          this.isEdit = false;
        }
      } else if (this.step === 1) {
        // 第二步
        this.formDataSessiom = this.$refs.sessiomForm;
        if (!this.formDataSessiom.selectSessiom) {
          uni.showToast({
            title: '请选择场次',
            duration: 3000,
            icon: 'none'
          });
        } else {
          // 提交表单
          this.submitForm();
        }
      }
    },
    async submitForm() {
      let that = this;
      let res;
      let session_id = this.formDataSessiom.selectSessiom;
      if (!this.isEdit) {
        let {name,sex,mobile} = this.formDataUserInfo;
        // 更新信息
        this.$u.vuex("vuex_userInfo", {
          name,
          mobile,
          sex,
          session_id
        });
        //新增
        res = await this.$u.api.TASAKIBOOKAPI.joinSession({
          name,
          sex,
          mobile,
          session_id,
          openid: this.vuex_wechatInfo.openId
        })
      } else {
        // 更新信息
        this.$u.vuex("vuex_userInfo.session_id", session_id);
        //修改
        res = await this.$u.api.TASAKIBOOKAPI.changeSession({
          session_id,
          openid: this.vuex_wechatInfo.openId
        })
      }
      if (res.status === 200) {
        wx.requestSubscribeMessage({
          tmplIds: ['HA9nRdmeRAwXrHN2r0K1pYdnzAJAhHvpj-ntVAwoInQ'],
          complete (res) {
            that.step ++
          }
        })
      } else {
        uni.showToast({
          title: res.msg,
          duration: 3000,
          icon: 'none'
        });
      }
    },
    userHandler(val) {
      if (val === 1) {
        // 回首页
        uni.reLaunch({
            url: `/pages/activityDetail/index`
        });
      } else if (val === 2) {
        // 修改时间
        this.step = 1;
        this.isEdit = true;
      } else if (val === 3) {
        //取消预约
        this.cancelSession();
      }
    },
    cancelSession() {
      let that = this;
      uni.showModal({
				title: '提示',
				content: '您确定要取消预约吗？',
				success: async (res) => {
          if (res.confirm) {
            that.$u.api.TASAKIBOOKAPI.cancelSession({
              openid: that.vuex_wechatInfo.openId
            }).then(res =>{
              uni.showToast({
                title: '取消预约成功',
                duration: 3000,
                icon: 'success'
              });
              setTimeout(_=>{
                that.$u.vuex("vuex_userInfo.session_id", '');
                that.$u.vuex("vuex_sessionInfo", {});
                uni.reLaunch({
                    url: `/pages/activityDetail/index`
                });
              },3000)
            })
          }
        }
      })
    },
    goSaveImg() {
      wx.showLoading({
        title: '图片生成中',
      })
      // 延迟500ms没有初始化完毕就去调用，会报错。
      setTimeout(_=>{
        try {
          let replaceWxml = wxml.replace("{{name}}", `${this.vuex_userInfo.name} ${this.vuex_userInfo.sex === 0 ? '先生' : '女士'}`)
          .replace("{{sessionDate}}", this.vuex_sessionInfo.session_date)
          .replace("{{sessionTime}}", this.vuex_sessionInfo.session_time);
          const p1 = this.widget.renderToCanvas({ wxml: replaceWxml, style })
          p1.then( _=> {
            const p2 = this.widget.canvasToTempFilePath();
            p2.then(res => {
              wx.hideLoading();
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success () {
                  uni.showToast({
                    title: '保存相册成功',
                    duration: 3000,
                    icon: 'success'
                  });
                },
                fail() {
                  uni.showToast({
                    title: '保存相册失败',
                    duration: 3000,
                    icon: 'error'
                  });
                }
              })
            })
          })
        } catch(err) {
          wx.hideLoading();
          uni.showToast({
            title: '保存相册失败',
            duration: 3000,
            icon: 'error'
          });
        }
      }, 500)
    },
    pageScrollToBottom: function() {
      wx.createSelectorQuery().select('.sign-up-page').boundingClientRect(function(rect){
        console.log(rect,'rect')
        // 使页面滚动到底部
        wx.pageScrollTo({
          scrollTop: rect.bottom
        })
      }).exec()
    }
  },
  onShareAppMessage() {
    return {
      title: "即刻预约TASAKI彗星珠宝系列互动活动",
      imageUrl: "https://cdc-file.risechina.com/img/2021/11/1636000449401.png",
      path: `/pages/activityDetail/index`
    };
  }
}
</script>

<style lang="scss" scoped>
  .custom {
    width: 100%;
    height: 90px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
    background-color: #fff;
    padding-bottom: 10rpx;
    .btn-back {
      width: 18rpx;
      height: auto;
      padding: 0 35rpx;
      position: absolute;
      bottom: 30rpx;
      left: 0rpx;
    }
    .logo {
      width: 200rpx;
      height: auto;
    }
  }
  .banner {
    .img {
      width: 100%;
      height: auto;
    }
  }
  .title {
    padding: 70rpx 0;
    display: flex;
    flex-flow: column;
    align-items: center;
    .title-img {
      width: 550rpx;
      height: auto;
      margin-bottom: 70rpx;
    }
  }
  .form {
    padding: 60rpx 60rpx 250rpx 60rpx; 
  }
  .btns-fix-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 60rpx 60rpx 90rpx 60rpx;
    background-color: #fff;
    z-index: 999;
    .btn-sign-up {
      width: 100%;
      height: 90rpx;
      background-color: #3e3a39;
      text-align: center;
      line-height: 94rpx;
      color: #fff;
      font-size: 28rpx;
      font-family: HiraginoSansGB-W3;
    }
    .btns-box {
      display: flex;
      padding: 35rpx 0;
      .btn {
        width: 33%;
        text-align: center;
        line-height: 1;
        font-family: HiraginoSansGB-W3;
        font-size: 28rpx;
        &:nth-child(2) {
          border-left: 1px solid #999;
          border-right: 1px solid #999;
        }
      }
    }
  }
</style>